const Class = require("../models/Class");
const {
  filterProperty,
  pickerProperty,
  deepClone,
} = require("../utils/operateProperty");
const validate = require("validate.js");
const rule = {
  name: {
    presence: { allowEmpty: false },
    type: "string",
  },
  openDate: {
    presence: { allowEmpty: false },
    datetime: {
      dateOnly: true,
    },
  },
};
class ClassService {
  /* constructor() {
    this.init();
  }
  init() {
    Class.findAll().then((classes) => {
      if (classes.length === 0) {
        this.addClass({
          name: "一年级二班",
          openDate: "2024-03-07",
        });
      }
    });
  } */
  addClass(classObj) {
    classObj = pickerProperty(classObj, Object.keys(rule));
    return this.validateClassObj(classObj, async (val) => {
      const classInfo = await this.getClasseByName(val);
      if (classInfo) {
        return Promise.reject("this class is exist");
      }
    })
      .then(() => {
        // 判断数据库中是否有管理员，如果没有，自动添加一个默认管理员
        return Class.create(classObj);
      })
      .then(() => {
        console.log("添加班级成功");
      });
  }
  deleteClass(classId) {
    // 验证id
    const res = validate.single(classId, {
      presence: true,
      type: "integer",
    });
    if (res)
      return Promise.reject(["id can't be blank and must be of type integer"]);
    Class.destroy({
      where: {
        id: classId,
      },
    }).then(() => {
      console.log("删除成功");
    });
  }
  updateClass(id, classObj) {
    // 验证id
    const res = validate.single(id, {
      presence: true,
      type: "integer",
    });
    if (res)
      return Promise.reject(["id can't be blank and must be of type integer"]);
    classObj = pickerProperty(classObj, Object.keys(rule));
    return Class.findByPk(id)
      .then((calssinfo) => {
        if (!calssinfo) {
          return Promise.reject("this class is not exist");
        }
      })
      .then(() => {
        return Class.update(classObj, {
          where: {
            id: id,
          },
        });
      })
      .then(() => {
        console.log("更新成功");
      });
  }
  async getClasseByName(name) {
    const classObj = await Class.findOne({
      attributes: ["id", "name", "openDate"],
      where: {
        name: name,
      },
    });
    return JSON.parse(JSON.stringify(classObj))
  }
  // 获取所有班级
  async getClasses(page = 1, limit = 10) {
    const { count, rows } = await Class.findAndCountAll({
      attributes: ["id", "name", "openDate"],
      offset: (page - 1) * limit,
      limit: limit,
    });
    return {
      total: count,
      datas: JSON.parse(JSON.stringify(rows)),
    };
  }

  validateClassObj(classObj, validator) {
    const rules = deepClone(rule);
    rules.name.exist = {
      validator,
    };
    return validate.async(classObj, rules);
  }
}

const classService = new ClassService();
module.exports = classService;
